/*************************************************************************
    > File Name: io_control.c
    > Author: Zehong Lee
    > Mail: hong2010.li@gmail.com  
    > Created Time: Sun 01 Sep 2013 04:33:50 PM HKT
 ************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

static int back_iopos(FILE *stream, int nchar)
{
	if(stream == NULL)
		return -1;

	int i = 0;

	for(i=0;i<nchar;i++)
	{// del n chars from the stream
		fputc(127, stream);
	}

	return 0;
}

// display completed percent value api
static int display_completed_percent(int len, int value)
{
	char buf[64]={0};
	int buf_len = 0;

	back_iopos(stdout,len);
	snprintf(buf,sizeof(buf),"completed ... %d%%",value);
	buf_len = strlen(buf);
	fprintf(stdout,"%s",buf); 
	fflush(stdout);

	return buf_len;
}

// should from 0% starting every time
static int display_completed_percent_easy(int value)
{
	char buf[64]={0};
	static int len = 0;

	if(value > 0)
		back_iopos(stdout,len);
	else 
		len = 0;
	snprintf(buf,sizeof(buf),"completed ... %d%%",value);
	len = strlen(buf);
	fprintf(stdout,"%s",buf); 
	fflush(stdout);

	return len;
}

int main(int argc, char **argv)
{
	int ret = 0;
	int i = 0, speed = 1000000;// speed unit is us
	char buf[128]={0};

	if(argc >= 2)
		speed = atoi(argv[1]);
#if 0
	strcpy(buf,"completed ... 0%");
	fprintf(stdout,"%s",buf); 
	fflush(stdout);
	int len = strlen(buf);
	for(i=1;i<=100;i++)
	{
#if 0
		back_iopos(stdout,len);
		snprintf(buf,sizeof(buf),"completed ... %d%%",i);
		len = strlen(buf);
		fprintf(stdout,"%s",buf); 
		if(i%10==0)
			fflush(stdout);
		usleep(speed);
#endif 
#if 0
		if(i%10==0)
			len = display_completed_percent(len,i);
		usleep(speed);
#endif
	}
#endif
	for(i=0;i<=100;i++)
	{
		if(i%10==0)
			display_completed_percent_easy(i);
		usleep(speed);
	}
	fprintf(stdout,"\n"); 

	return ret;
}

